<template>
  <div class="overlay"  v-show="show" @click="$emit('overlay-click')" @touchmove.prevent>
    <div class="menu" :style="style" ref="menu">
      <div class="menu-item" v-for="action in actions" :key="action.key" @click="$emit('menu-click',action.key)">
        <van-icon class="icon" :name="action.icon"></van-icon>
        <div class="text van-hairline--bottom">{{ action.text }}</div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'PopMenu',
  data() {
    return {
      viewSize: {
        width: 0,
        height: 0
      },
      style: {},
      offset: {
        x: 10,
        y: 10
      }
    }
  },
  props: {
    show: Boolean,
    coordinate: {
      type: Object,
      default() {
        return {
          x: 0,
          y: 0
        }
      }
    },
    actions: {
      type: Array,
      default() {
        return []
      }
    }
  },
  watch: {
    show(newval) {
      this.$nextTick(() => {
        this.style = this.getStyle()
      })
    }
  },
  computed: {

  },
  created() {
    this.getViewSize()
    window.addEventListener('resize', this.getViewSize)
  },
  methods: {
    getMenuSize() {
      let [width, height] = [0, 0]
      if (this.$refs.menu) {
        width = this.$refs.menu.offsetWidth
        height = this.$refs.menu.offsetHeight
      }
      // this.menuSize.width = width
      // this.menuSize.height = height
      return { width, height }
    },
    getViewSize() {
      this.viewSize.width = window.innerWidth
      this.viewSize.height = window.innerHeight
    },
    getStyle() {
      const menuSize = this.getMenuSize()
      const left = this.coordinate.x - menuSize.width <= 10
        ? this.coordinate.x
        : this.coordinate.x - menuSize.width
      const top = this.coordinate.y + menuSize.height >= this.viewSize.height - 10
        ? this.coordinate.y - menuSize.height
        : this.coordinate.y
      return {
        transform: this.show ? 'scale(1)' : 'scale(0)',
        left: `${left}px`,
        top: `${top}px`
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.overlay {
  width: 100vw;
  height: calc(var(--vh) * 100);
  position: fixed;
  left: 0;
  top: 0;
  z-index: 999;
  .menu {
    position: absolute;
    transition: transform 0.25s;
    background-color: #fff;
    box-shadow: 0 2px 12px #3232331f;
    padding: $padding-side;
    .menu-item{
      // height: 40px;
      display: flex;
      align-items: center;
      font-size: $font-size-lg;
      .icon{
        margin-right: $padding-side;
      }
      .text{
        padding:$padding-side 0;
      }
    }
  }
}
</style>
